﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using MobileBroadbandLoggingMonitorGUI.Interfaces;
using MobileBroadbandLoggingMonitorUI.Interfaces;
using System.Collections.Specialized;
using System.Web;

namespace MobileBroadbandLoggingMonitorGUI.Implementations
{
    public class ServerCommunication : IServerCommunication
    {
        private ISettings _settings;
        public ServerCommunication(ISettings settings)
        {
            _settings = settings;
        }
        public override void SendSharedInformationToServer(string mobileBroadbandProviderName, string mobileSoftwareName, string informationToShare, string email)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            NameValueCollection postContent = new NameValueCollection();

            postContent.Add("mobileBroadbandProviderName", mobileBroadbandProviderName);
            postContent.Add("mobileSoftwareName", mobileSoftwareName);
            postContent.Add("informationToShare", informationToShare);
            postContent.Add("email", email);

            byte[] data = encoding.GetBytes(GetPostDataString(postContent));
            string postUrl = "http://apps.mobilebroadbanduser.eu/CommitSharedInformation.aspx";

            SendPostDataToEndpoint(postUrl, data);
        }

        public override void SendSharedInformationToServer(string informationToShare)
        {
            this.SendSharedInformationToServer(string.Empty, string.Empty, informationToShare, string.Empty);
        }

        private void SendPostDataToEndpoint(string postUrl, byte[] data)
        {
            HttpWebRequest myRequest = (HttpWebRequest) WebRequest.Create(postUrl);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            using (Stream newStream = myRequest.GetRequestStream())
            {
                // Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();
            }
        }

        private string GetPostDataString(NameValueCollection postContent)
        {
            string postDataString = string.Empty;
            foreach (string key in postContent.Keys)
            {
                if (!string.IsNullOrEmpty(postDataString))
                {
                    postDataString += "&";
                }
                postDataString += string.Format("{0}={1}", key, HttpUtility.UrlEncode(postContent[key]));
            }
            return postDataString;
        }
    }
}
